package com.doordu.soa.service.web.utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BeanHelper {
	private  static final Logger logger = LoggerFactory.getLogger(BeanHelper.class);
	/**
	 * 复制对象
	 * @param from
	 * @param c
	 * @return
	 */
	public static Object copy(Object from,Class<?> c){
		Map<String, Object> data = objectToMap(from);
		return mapToObject(data, c);
	}
	
	/**
	 * 将实体对象转换map
	 * @param object
	 * @return
	 */
	public static Map<String, Object> objectToMap(Object object){
		Map<String, Object> map = new TreeMap<String,Object>();
		try {  
            BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());  
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
            for (PropertyDescriptor property : propertyDescriptors) {  
                String key = property.getName();  
   
                if (!key.equals("class")) {  
                    // 得到property对应的getter方法  
                    Method getter = property.getReadMethod();  
                    Object value = getter.invoke(object);  
                    if(value == null){
                    	continue;
                    }
                    map.put(key, value);
                }  
            }  
        } catch (Exception e) {  
           logger.error("",e);
        }  
		return map;
	}
	
	/**
	 * 将map对象转换为object
	 * @param map
	 * @param c
	 * @return
	 */
	public static Object mapToObject(Map<String, Object> map,Class<?> c){
		Object object = null;
		try {
			object = c.newInstance();
			BeanUtils.populate(object, map); 
		} catch (InstantiationException e) {
			logger.error("",e);
		} catch (IllegalAccessException e) {
			logger.error("",e);
		} catch (Exception e) {  
			logger.error("",e);
        }
        return object;
	}
}
